//
//  DYChatViewController.m
//  HBuilder
//
//  Created by 黄德玉 on 2019/11/2.
//  Copyright © 2019 DCloud. All rights reserved.
//

#import "DYChatViewController.h"
#import "DYIMChatNavView.h"
#import "Masonry.h"
#import "KxMenu.h"
#import "UIView+MBProgressHUD.h"
#import "DYGlobal.h"
#import "DYZXViewController.h"
#import "AppDelegate.h"
#import "EBHCountDownView.h"
#import "AFNetworking.h"
#import "EBHNetWorkingManager.h"
#import "EBHEndChatView.h"

@interface DYChatViewController ()<UIAlertViewDelegate>

@property (nonatomic ,strong) DYIMChatNavView * navBar;
@property (nonatomic, strong) UIButton * rightBtn;
@property (nonatomic, strong) EBHCountDownView * countDownView;
@property (nonatomic, strong) EBHEndChatView * endChatView;

@end

@implementation DYChatViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.navBar];
    CGFloat height = 64.0;
    if ([DYGlobal isNotchScreen]) {
        height = 88.f;
    }
    [self.navBar mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.top.right.equalTo(self.view);
       make.height.equalTo(@(height));
   }];
    self.navBar.titleLabel.text = self.ebh_userName;
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.rightBtn setImage:[UIImage imageNamed:@"more"] forState:UIControlStateNormal];
    [self.navBar addSubview:self.rightBtn];
    [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.navBar.titleLabel);
        make.right.equalTo(self.navBar).offset(-16);
    }];
    [self.rightBtn addTarget:self action:@selector(rightNavClicked) forControlEvents:UIControlEventTouchUpInside];
    if (self.ebh_status) {
        [self countDownView];
    } else {
        [self endChatView];
        self.countDownView.hidden = YES;
        self.endChatView.hidden = NO;
    }
    [self.pluginBoardView removeItemAtIndex:2];
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    if (self.didPopBlock) {
        self.didPopBlock();
    }
    
}

- (void)countDownTap{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否结束咨询" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)panGestureAction:(UIPanGestureRecognizer *)panGesture{
    CGPoint center = [panGesture locationInView:nil];
    CGFloat centerY = center.y;
    if (center.y < YG_NAVIGATION_BAR_HEIGHT + 20) {
        centerY = YG_NAVIGATION_BAR_HEIGHT + 20;
    }
    if ([UIScreen mainScreen].bounds.size.height - center.y < YG_TAB_BAR_HEIGHT + 20) {
        centerY = [UIScreen mainScreen].bounds.size.height - YG_TAB_BAR_HEIGHT - 20;
    }
    self.countDownView.center = CGPointMake(self.countDownView.center.x, centerY);
    switch (panGesture.state) {
        case UIGestureRecognizerStateEnded:{
            
        }
            break;
            
        default:
            break;
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex > 0) {
        __weak typeof(self)weakSelf = self;
        
        [EBHNetWorkingManager queryWithPath:@"/sapi/rongyun/chatEnd" pars:@{@"to":self.targetId} callback:^(NSError * _Nonnull error, id  _Nonnull response) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.view showHUDMessage:@"操作成功"];
            });
                           
            if (error) {
               NSLog(@"Error: %@", error);
            } else {
               NSLog(@"%@", response);
               [weakSelf endChatView];
               weakSelf.countDownView.hidden = YES;
               weakSelf.endChatView.hidden = NO;
            }
        }];
    }
}

- (void)rightNavClicked{
    KxMenuItem * item = [KxMenuItem menuItem:@"更改咨询费" image:nil target:self action:@selector(firstItemClicked)];
    item.foreColor = [UIColor whiteColor];
    KxMenuItem  * item1 =  [KxMenuItem menuItem:@"清除聊天记录" image:nil target:self action:@selector(clearRecord)];
    item1.foreColor = [UIColor whiteColor];
    [KxMenu showMenuInView:self.view fromRect:self.rightBtn.frame menuItems:@[item ,item1]];
//    [KxMenu showMenuInView:self.view fromRect:CGRectMake(82,40,50, 25) menuItems:@[item ,item1]];
}

- (void)firstItemClicked{
    // 更改咨询费
    DYZXViewController * vc = [DYZXViewController new];
     UINavigationController * nav = (UINavigationController *)(AppDelegate *)[UIApplication sharedApplication].delegate.window.rootViewController;
    vc.targetId = self.targetId;
    [nav pushViewController:vc animated:YES];
}

- (void)clearRecord{
    // 清除聊天记录
    __weak typeof(self)weakSelf = self;
    [[RCIMClient sharedRCIMClient] deleteMessages:ConversationType_PRIVATE targetId:self.targetId success:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.view showHUDMessage:@"清除聊天记录成功"];
        });
    } error:^(RCErrorCode status) {

    }];
}

- (DYIMChatNavView *)navBar{
   if (!_navBar) {
          _navBar = [[DYIMChatNavView alloc] init];
          __weak typeof(self)weakSelf = self;
          _navBar.itemClicked = ^(NSInteger tag) {
              [weakSelf.navigationController popViewControllerAnimated:YES];
          };
          if (self.title) {
              _navBar.titleLabel.text = self.title;
          }
      }
      return _navBar;
}

- (EBHCountDownView *)countDownView{
    if (!_countDownView) {
        _countDownView = [[EBHCountDownView alloc] initWithCountDown:self.ebh_CountDown];
        if (self.ebh_CountDown == 0) {
            _countDownView.hidden = YES;
        }
        [self.view addSubview:_countDownView];
//        [_countDownView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.right.equalTo(self.view);
//            make.bottom.equalTo(self.view).offset(-245);
//        }];
        _countDownView.frame = CGRectMake(270, 610, 144, 41);
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(countDownTap)];
        [_countDownView addGestureRecognizer:tap];
        
        UIPanGestureRecognizer * panGes = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureAction:)];
        [_countDownView addGestureRecognizer:panGes];
        [tap requireGestureRecognizerToFail:panGes];
    }
    return _countDownView;
}


- (EBHEndChatView *)endChatView{
    if (!_endChatView) {
        _endChatView = [EBHEndChatView new];
        _endChatView.hidden = NO;
        [self.view addSubview:_endChatView];
        [_endChatView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.view);
        }];
        
        __weak typeof(self)weakSelf = self;
        _endChatView.tapActionBlcok = ^{
            [weakSelf.view endEditing:YES];
            [EBHNetWorkingManager queryWithPath:@"/sapi/rongyun/chat" pars:@{@"to":weakSelf.targetId} callback:^(NSError * _Nonnull error, id  _Nonnull response) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.view showHUDMessage:@"操作成功"];
                });
                
                if (error) {
                    NSLog(@"Error: %@", error);
                } else {
                    NSLog(@"%@", response);
                    weakSelf.countDownView.hidden = NO;
                    NSInteger expiryDate = [[response objectForKey:@"expiryDate"] integerValue];
                    [weakSelf.countDownView updateCountDown:expiryDate];
                    weakSelf.endChatView.hidden = YES;
                }
            }];
        };
    }
    return _endChatView;
}

@end
